package com.yangtu.nearbyshop.wx.util;

import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import java.util.*;
import java.util.Map.Entry;

public class XmlHelper {

	private static final Logger _LOG = LoggerFactory.getLogger(XmlHelper.class);
	/**
	 * <xml>
		   <appid>wx2421b1c4370ec43b</appid>
		   <attach>支付测试</attach>
		   <body>APP支付测试</body>
		   <mch_id>10000100</mch_id>
		   <nonce_str>1add1a30ac87aa2db72f57a2375d8fec</nonce_str>
		   <notify_url>http://wxpay.wxutil.com/pub_v2/pay/notify.v2.php</notify_url>
		   <out_trade_no>1415659990</out_trade_no>
		   <spbill_create_ip>14.23.150.211</spbill_create_ip>
		   <total_fee>1</total_fee>
		   <trade_type>APP</trade_type>
		   <sign>0CB01533B8C1EF103065174F50BCA001</sign>
		</xml>
	 * @throws ParserConfigurationException
	 * @throws TransformerException
	 */

	public static String createXmlStr(Map<String, String> content) {
		if (content != null && content.size() > 0) {
			Map<String, String> params = new TreeMap<String, String>(new Comparator<String>() {
				public int compare(String s1, String s2) {
					return s1.compareTo(s2);
				}
			});
			params.putAll(content);
			StringBuilder builder = new StringBuilder(200);
			builder.append("<xml>");
			for (Iterator<Entry<String, String>> iterator = params.entrySet().iterator(); iterator.hasNext();) {
				Entry<String, String> next = iterator.next();
				if (!"sign".equals(next.getKey())) {
					builder.append("<").append(next.getKey()).append(">").append(next.getValue()).append("</").append(next.getKey()).append(">");
				}
			}
			builder.append("<sign>" +params.get("sign")+"</sign>");
			builder.append("</xml>");
			return builder.toString();
		}
		return null;

	}


	/**
	 * 将xml字符串转成bean类
	 * @param xmlContent
	 * @param type
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static <T> T parseXmlBean(String xmlContent, Class<T> type) throws Exception {
		org.dom4j.Document document = DocumentHelper.parseText(xmlContent);
		Element root = document.getRootElement();
		List<Element> eles = root.elements();
		Map<String, String> data = Maps.newHashMap();
		for (Element ele : eles) {
			if (Strings.isNullOrEmpty(ele.getTextTrim())) continue;
			data.put(ele.getName(), ele.getTextTrim());
		}
		String bean2Json = JsonUtils.bean2Json(data);
		T t = (T) JsonUtils.json2Bean(bean2Json, type);
		return t;
	}

}
